<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Title</title>
  </head>
  <body>
    <div class="box"></div>
  </body>
  <script type="text/javascript">
    class Drag {
      constructor(target, flag = true) {
        this.dom = document.querySelector(target);
        this.domPos = { x: 0, y: 0 };
        this.flag = flag;
        this.init();
        this.up();
      }
      init() {
        this.dom.onmousedown = this.down.bind(this);
      }
      //按下
      down(e) {
        let event = e || window.event;
        console.log(this.dom);
        this.dom.setAttribute("class", "box move");
        this.domPos = {
          x: event.offsetX,
          y: event.offsetY,
        };
        document.onmousemove = this.move.bind(this);
      }
      //移动
      move() {
        let pos = this.setPos();
        this.dom.style.transform =
          "translate(" + pos.x + "px, " + pos.y + "px)";
      }
      //计算距离
      setPos(e) {
        let event = e || window.event;
        let { domPos } = this;
        let pos = {
          x: event.clientX - domPos.x,
          y: event.clientY - domPos.y,
        };
        return this.setMax(pos);
      }
      //最大宽高限制
      setMax(pos) {
        let maxW = document.documentElement.clientWidth - this.dom.clientWidth;
        let maxH =
          document.documentElement.clientHeight - this.dom.clientHeight;
        if (pos.x <= 0) pos.x = 0;
        if (pos.y <= 0) pos.y = 0;
        if (pos.x >= maxW) pos.x = maxW;
        if (pos.y >= maxH) pos.y = maxH;
        return pos;
      }
      //鼠标抬起
      up() {
        let _this = this;
        document.onmouseup = function up() {
          document.onmousemove = null;
          _this.dom.setAttribute("class", "box");
        };
      }
    }
    /*
    @String  元素类名
    @Boolen  true全局移动  false在父元素移动  默认true
    */
    new Drag(".box", true);
  </script>
  <style>
    .box {
      width: 200px;
      height: 200px;
      background-color: deeppink;
    }
    .move {
      cursor: move;
    }
  </style>
</html>
